<template>
    <div class="app-container">
        <el-form :model="listQuery" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="用户ID" prop="search">
                <el-input
                    v-model="listQuery.id"
                    label="请输入用户名称"
                    placeholder="请输入用户名称"
                    style="width: 200px;"
                    class="filter-item"
                    @keyup.enter.native="handleFilter"
                />
            </el-form-item>
            <el-form-item label="账号状态" prop="flag">
                <el-select label="账号状态" v-model="listQuery.flag" placeholder="请选择状态" clearable class="filter-item">
                    <el-option v-for="dict in dict.type.sys_normal_flag" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="身份" prop="role">
                <el-select label="身份" v-model="listQuery.role" placeholder="请选择身份" clearable class="filter-item">
                    <el-option v-for="dict in dict.type.sys_user_water_role" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleFilter">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getUserList"></right-toolbar>
        </el-row>

        <el-table
            v-loading="listLoading"
            :data="userList"
            :element-loading-text="elementLoadingText"
            @selection-change="setSelectRows"
            border
            class="margin-buttom-10"
        >
            <el-table-column show-overflow-tooltip type="selection"/>
            <el-table-column
                show-overflow-tooltip
                prop="id"
                label="编号"
                align="center"
            />
            <el-table-column label="用户名称/手机号" show-overflow-tooltip align="center">
                <template slot-scope="{ row }">
                    {{ row.nickname }}/{{ row.mobile }}
                </template>
            </el-table-column>
<!--            <el-table-column label="身份" align="center" prop="water_role"  >
                <template slot-scope="{row}">
                    <dict-tag :options="dict.type.sys_user_water_role" :value="row.water_role" />
                </template>
            </el-table-column>-->
            <el-table-column label="注册时间" show-overflow-tooltip align="center">
                <template slot-scope="{ row }">
                    {{ row.created_time }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="flag" label="账号状态">
                <template slot-scope="{row}">
                    <dict-tag :options="dict.type.sys_normal_flag" :value="row.flag" />
                </template>
            </el-table-column>
            <el-table-column  fixed="right" label="操作" align="center" >
                <template v-slot="{row}">
                    <!-- 编辑与删除 -->
                    <el-button  type="text" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                    <el-dropdown  @command="(command) => handleCommand(command, row)" >
                        <el-button  type="text" icon="el-icon-d-arrow-right">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
<!--                            <el-dropdown-item command="handleUserIntegra" icon="el-icon-circle-check">查看积分</el-dropdown-item>-->
<!--                            <el-dropdown-item command="handleUserWater" icon="el-icon-circle-check">分配水机</el-dropdown-item>-->
                            <el-dropdown-item command="handleModifyEdit" icon="el-icon-circle-check">变更身份</el-dropdown-item>
                            <el-dropdown-item command="handleRechargeRecord"  icon="el-icon-circle-check">充值记录</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getUserList"
        />

        <!-- 变更身份 -->
        <el-dialog :visible.sync="dialogModifyVisible" title="编辑身份">
            <el-form ref="formModify" :model="formModify" label-width="150px">
                <el-form-item label="用户名称：" prop="nickname">
                    <div>{{ formModify.nickname }}</div>
                </el-form-item>
                <el-form-item label="手机号：" prop="mobile">
                    <div>{{ formModify.mobile }}</div>
                </el-form-item>
                <el-form-item label="水机身份" prop="water_intake">
                    <el-radio-group v-model="formModify.water_role">
                        <el-radio
                            v-for="dict in dict.type.sys_user_water_role"
                            :key="dict.value"
                            :label="dict.value"
                        >{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div style="text-align:right;">
                <el-button type="danger" @click="dialogModifyVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmModifyRole">提交</el-button>
            </div>
        </el-dialog>
        <!-- 详情 -->
        <el-dialog :visible.sync="openUser" :title="titleUser">
            <el-form ref="formUser" :model="formUser" :rules="formUserRole"  label-width="150px">
                <el-form-item label="用户ID" v-show="formUser.id != 0">
                    <el-input v-model="formUser.id" :disabled="formUser.id !=0" placeholder="用户id"/>
                </el-form-item>
                <el-form-item label="用户名/账户">
                    <el-input v-model="formUser.username" :disabled="formUser.id !=0" placeholder="用户名"/>
                </el-form-item>
                <el-form-item label="昵称/姓名">
                    <el-input v-model="formUser.nickname" placeholder="昵称/姓名"/>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="formUser.mobile" placeholder="手机号"/>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="formUser.password" placeholder="密码"/>
                </el-form-item>
                <el-form-item label="是否启用" prop="flag">
                    <el-radio-group v-model="formUser.flag">
                        <el-radio
                            v-for="dict in dict.type.sys_normal_flag"
                            :key="dict.value"
                            :label="dict.value"
                        >{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="水机身份" prop="water_intake">
                    <el-radio-group v-model="formUser.water_role">
                        <el-radio
                            v-for="dict in dict.type.sys_user_water_role"
                            :key="dict.value"
                            :label="dict.value"
                        >{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div style="text-align:right;">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

import {getUsersIntakeList,detailIntakeUsers,createUsers,updateUsers,modifyUsersRole} from "@/api/grzq/user_intake";

export default {
    name: 'UserManagement',
    dicts:['sys_normal_disable','sys_normal_flag','sys_user_water_role'],
    data() {
        return {
            is_batch: 0, // 默认不开启批量删除
            userList: [],
            showSearch: true,
            listLoading: true,
            layout: 'total, sizes, prev, pager, next, jumper',
            total: 0,
            selectRows: '',
            elementLoadingText: '正在加载...',
            listQuery: {
                page: 1,
                limit: 10,
                id: '',
                nickname: '',
                flag: '',
                role: '',
                is_check: '',
            },
            downloadLoading: false,
            // 变更身份
            dialogModifyVisible:false,
            // 弹出层标题
            titleUser: "",
            titleWater: "分配水机",
            // 是否显示弹出层
            openWater: false,
            openUser: false,

            // 详情
            dialogType: 'add',
            checkStrictly: false,
            dialogVisible: false,
            formModify: {},
            formUser: {},
            formUserRole: {
                username: [
                    { required: true, message: "用户名/账户不能为空", trigger: "blur" }
                ],
                nickname: [
                    { required: true, message: "昵称/姓名不能为空", trigger: "blur" }
                ],
                mobile: [
                    { required: true, message: "手机号不能为空", trigger: "blur" }
                ],
            }
        }
    },
    computed: {

    },
    created() {
        // 获取角色用户列表
        this.getUserList();

    },
    methods: {
        reset(){
            this.formUser = {
                id: 0,
                username: '',
                nickname: '',
                mobile: '',
                water_role:'intake',
                is_check: "0",
            };
            this.resetForm('formUser')
        },
        resetModify(){
            this.formModify = {
                water_role:'',
            };
            this.resetForm('formModify')
        },

        // 获取用户列表
        async getUserList(callback) {
            this.listLoading = true;
            const {data, status, msg} = await getUsersIntakeList(this.listQuery);
            this.userList = data.data;
            this.total = data.total;
            this.listQuery.limit = data.per_page || 10;
            this.listLoading = false;

        },
        setSelectRows(val) {
            this.selectRows = val;
            this.is_batch = 1;
        },
        handleModifyEdit(row) {
            this.resetModify()
            this.dialogModifyVisible = true;
            this.formModify = Object.assign({}, row);
        }, // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleModifyEdit":
                    //修改身份
                    this.handleModifyEdit(row);
                    break;
                case "handleUserWater":
                    this.handleUserWater(row);
                    break;
                case "handleUserIntegra":
                    this.handleUserIntegra(row);
                    break;
                case "handleRechargeRecord":
                    // 充值记录
                    // this.handleUserIntegra(row);
                    break;
                case "handleWithdrawalRecord":
                    // 提现记录
                    // this.handleUserIntegra(row);
                    break;
                default:
                    break;
            }
        },

        handleAdd() {
            this.reset()
            this.openUser = true;
            this.titleUser = '新增用户';
        },
        handleEdit(row) {
            const detail = Object.assign({}, row);
            this.reset()
            this.openUser = true;
            this.titleUser = '编辑用户';
            this.formUser.id = detail.id,
                this.formUser.username = detail.username;
            this.formUser.nickname = detail.nickname;
            this.formUser.mobile = detail.mobile;
            this.formUser.water_role = detail.water_role;
            this.formUser.flag = detail.flag.toString()

        },

        handleSizeChange(val) {
            this.listQuery.limit = val;
            this.getUserList();
        },
        handleCurrentChange(val) {
            this.listQuery.page = val;
            this.getUserList();
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getUserList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleFilter();
        },
        editRole(formName) {
            let that = this;
            this.$nextTick(function () {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        this.$confirm(`调整用户身份将影响水机绑定情况与积分分成`, "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning",
                        }).then(async () => {
                            const res = await modifyUsersRole(that.formModify );
                            this.dialogVisible = false;
                            this.$message({
                                type: "success",
                                message: "操作成功!",
                            });
                            await that.getData();
                        }).catch((err) => {
                            console.error(err);
                        });
                    } else {
                        return false;
                    }
                });
            });
        },

        // 变更身份
        async confirmModifyRole() {
            let that = this;
            that.$refs['formModify'].validate(async (valid) => {
                if (valid) {
                    const {msg, status} =  await modifyUsersRole({"id":that.formModify.id, "water_role":that.formModify.water_role,})
                    switch (status) {
                        case 1:
                            this.$message({
                                message: msg,
                                type: 'success'
                            });
                            if (this.role.id) that.getList();
                            break;
                        default:
                            this.$notify({
                                title: msg,
                                // dangerouslyUseHTMLString: true,
                                type: 'error'
                            });
                            break;
                    }
                    this.dialogVisible = false;
                } else {
                    return false;
                }
            });
        },

        submitForm: function() {
            this.$refs["formUser"].validate(valid => {
                if (valid) {
                    if (this.formUser.id != 0) {
                        updateUsers(this.formUser).then(response => {
                            this.msgSuccess("修改成功");
                            this.openUser = false;
                            this.getUserList();
                        });
                    } else {
                        createUsers(this.formUser).then(response => {
                            this.msgSuccess("新增成功");
                            this.openUser = false;
                            this.getUserList();
                        });
                    }
                }
            });
        },
        /** 分配角色操作 */
        handleUserWater: function(row) {
            const userId = row.id;
            var query = {};
            query.userId = userId;
            this.$router.push({
                'path':`/member/userWater`,
                'query': query,
            });
        },
        /** 分配角色操作 */
        handleUserIntegra: function(row) {
            const userId = row.id;
            var query = {};
            query.userId = userId;
            this.$router.push({
                'path':`/member/userIntegra`,
                'query': query,
            });
        },

        // 状态变更
        async changeStatus(row, value) {
            const {data, msg, status} = await changeFiledStatus({
                'id': row.id,
                'change_field': 'is_check',
                'change_value': value
            });
            // 设置成功之后，同步到当前列表数据
            if (status == 1) row.is_check = value;
            this.$message({
                message: msg,
                type: status == 1 ? 'success' : 'error',
            });
        },

    },
}
</script>
